import request from "@/utils/request";
import { useSettingsStore } from "@/store";

const settingStore = useSettingsStore();

const BASE_URL = `/api/${settingStore.elementRoutePrefix}/device`;

const DeviceAPI = {
  // 获取设备列表
  getDevices(deviceType?: string, isEnabled?: boolean) {
    const formData = new FormData();
    formData.append("deviceType", deviceType ?? "");
    formData.append("isEnable", (isEnabled ?? "").toString());
    return request<any, DeviceConfig[]>({
      url: `${BASE_URL}/GetDevices/`,
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },

  /**
   * 获取某个工作位的设备
   * @param stationNum 工位号
   */
  getStationDevices(stationNum: number) {
    const formData = new FormData();
    formData.append("stationNum", stationNum.toString());
    return request<any, DeviceConfig[]>({
      url: `${BASE_URL}/GetDevicesByStationNum/`,
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },

  /**
   * 获取工位数量上限
   */
  getRealStationCount() {
    return request<any, number>({
      url: `${BASE_URL}/GetRealStationCount/`,
      method: "post",
    });
  },

  // 获取设备配置
  getDeviceConfig(id: number) {
    return request<any, DeviceConfig>({
      url: `${BASE_URL}/Get/${id}`,
      method: "post",
    });
  },

  // 获取串口列表
  getComPorts() {
    return request<any, string[]>({
      url: `${BASE_URL}/GetComPorts`,
      method: "post",
    });
  },

  // 获取设备类型和型号
  getDeviceTypeAndModes() {
    return request<any, KeyValueItem[]>({
      url: `${BASE_URL}/GetDeviceTypeAndModes`,
      method: "post",
    });
  },

  // 获取设备连接状态
  getAllDeviceConnectStatus() {
    return request<any, Array<{ key: number; value: boolean }>>({
      url: `${BASE_URL}/GetDeviceConnectStatus/`,
      method: "post",
    });
  },

  // 添加或修改设备配置
  modifyDeviceConfig(deviceConfig: DeviceConfig) {
    return request<any, any>({
      url: `${BASE_URL}/AddOrUpdate`,
      method: "post",
      data: deviceConfig,
    });
  },

  // 删除设备
  delete(id: number) {
    return request<any, any>({
      url: `${BASE_URL}/Delete/${id}`,
      method: "post",
    });
  },

  // 连接设备
  connect(id: number) {
    return request<any, boolean>({
      url: `${BASE_URL}/TryConnect/${id}`,
      method: "post",
    });
  },

  // 断开连接
  disconnect(id: number) {
    return request<any, boolean>({
      url: `${BASE_URL}/Disconnect/${id}`,
      method: "post",
    });
  },
};

export default DeviceAPI;
